package com.ruoyi.web.service;

import com.easemob.im.server.model.EMUserStatus;
import com.ruoyi.app.domain.AppUser;
import com.ruoyi.app.domain.bo.AppUserBo;
import com.ruoyi.app.domain.vo.AppUserVo;
import com.ruoyi.app.service.IAppUserService;
import com.ruoyi.common.constant.Constants;
import com.ruoyi.common.core.domain.PageQuery;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.utils.spring.SpringUtils;
import com.ruoyi.im.core.EasemobTemplate;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Component
@Slf4j
public class AsyncCaller {

    @Autowired
    private IAppUserService iAppUserService;

    /**
     * 更新用户的在线状态
     */
    @Async
    public void updateUserLine() {
        AppUserBo appUserBo = new AppUserBo();
        appUserBo.setRegister(Constants.SUCCESS);
        List<AppUser> userVos = iAppUserService.queryListUser(appUserBo);
        int next = userVos.size() / 100;
        if (next == 0) {
            next = 1;
        }
        for (int i = 1; i <= next; i++) {
            PageQuery pageQuery = new PageQuery();
            pageQuery.setPageSize(100);
            pageQuery.setPageNum(i);
            TableDataInfo<AppUser> appUserVoTableDataInfo = iAppUserService.queryPage(appUserBo, pageQuery);
            List<AppUser> data = appUserVoTableDataInfo.getData();
            ArrayList<String> userNames = new ArrayList<>();
            data.forEach(e -> userNames.add(Constants.USER + e.getId()));
            Map<Long, AppUser> map = data.stream().collect(Collectors.toMap(AppUser::getId, appUser -> appUser));
            EasemobTemplate imTemplate = SpringUtils.getBean(EasemobTemplate.class);
            List<EMUserStatus> usersOnline;
            try {
                usersOnline = imTemplate.isUsersOnline(userNames);
            } catch (Exception e) {
                log.info("批量获取在线用户状态失败：{}", e.getMessage());
                return;
            }
            ArrayList<AppUser> updates = new ArrayList<>();
            usersOnline.forEach(e -> {
                Long id = Long.valueOf((e.getUsername().substring(5)));
                AppUser nowUser = map.get(id);
                if (e.isOnline() != (nowUser.getOnlineStatus().equals(Constants.FAIL))) {
                    nowUser.setOnlineStatus(e.isOnline() ? "1" : "0");
                    updates.add(nowUser);
                }
            });
            iAppUserService.update(updates);
        }
    }
}
